import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import '../repositories/auth_repository.dart';
import '../repositories/auth_repository_factory.dart';
import '../models/auth_token.dart';

class AuthInterceptor extends Interceptor {
  final AuthRepository _authRepository;
  final void Function()? onTokenExpired;

  AuthInterceptor({
    AuthRepository? authRepository,
    this.onTokenExpired,
  }) : _authRepository = authRepository ?? AuthRepositoryFactory.create();

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    print('📤 [AUTH_INTERCEPTOR] ${options.method} ${options.path}');
    
    // 跳过认证相关的请求，避免循环
    final skipAuthPaths = [
      '/api/auth/login',
      '/api/auth/register', 
      '/api/auth/refresh',
      '/api/auth/forgot-password',
    ];
    
    if (!skipAuthPaths.any((path) => options.path.contains(path))) {
      await _addAuthHeader(options);
    }
    
    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    print('📥 [AUTH_INTERCEPTOR] ${response.statusCode} ${response.requestOptions.path}');
    handler.next(response);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    print('❌ [AUTH_INTERCEPTOR] ${err.response?.statusCode} ${err.requestOptions.path} - ${err.message}');
    
    // 处理401未授权错误
    if (err.response?.statusCode == 401) {
      final refreshed = await _handleUnauthorized(err.requestOptions);
      
      if (refreshed) {
        // Token刷新成功，重试原请求
        try {
          print('🔄 [AUTH_INTERCEPTOR] Token刷新成功，重试请求...');
          final response = await _retry(err.requestOptions);
          return handler.resolve(response);
        } catch (e) {
          print('💥 [AUTH_INTERCEPTOR] 重试请求失败: $e');
          return handler.next(err);
        }
      } else {
        // Token刷新失败，触发登出
        print('🚪 [AUTH_INTERCEPTOR] Token刷新失败，触发登出');
        onTokenExpired?.call();
        return handler.next(err);
      }
    }
    
    handler.next(err);
  }

  /// 添加认证头
  Future<void> _addAuthHeader(RequestOptions options) async {
    try {
      final token = await _authRepository.getStoredToken();
      
      if (token != null) {
        // 检查Token是否即将过期
        if (token.isExpiringSoon && !token.isExpired) {
          print('⏰ [AUTH_INTERCEPTOR] Token即将过期，尝试刷新...');
          await _refreshTokenIfNeeded(token);
          
          // 获取刷新后的Token
          final refreshedToken = await _authRepository.getStoredToken();
          if (refreshedToken != null) {
            options.headers['Authorization'] = refreshedToken.authorizationHeader;
            print('✅ [AUTH_INTERCEPTOR] 使用刷新后的Token');
          } else {
            options.headers['Authorization'] = token.authorizationHeader;
            print('⚠️ [AUTH_INTERCEPTOR] Token刷新失败，使用原Token');
          }
        } else if (!token.isExpired) {
          options.headers['Authorization'] = token.authorizationHeader;
          print('🔑 [AUTH_INTERCEPTOR] 添加认证头: ${token.tokenType} ***${token.accessToken.substring(token.accessToken.length - 8)}');
        } else {
          print('⚠️ [AUTH_INTERCEPTOR] Token已过期，跳过添加认证头');
        }
      } else {
        print('🔓 [AUTH_INTERCEPTOR] 没有可用的Token');
      }
    } catch (e) {
      print('❌ [AUTH_INTERCEPTOR] 添加认证头失败: $e');
    }
  }

  /// 处理401未授权错误
  Future<bool> _handleUnauthorized(RequestOptions options) async {
    try {
      final token = await _authRepository.getStoredToken();
      
      if (token?.refreshToken != null) {
        return await _refreshTokenIfNeeded(token!);
      } else {
        print('⚠️ [AUTH_INTERCEPTOR] 没有可用的刷新Token');
        return false;
      }
    } catch (e) {
      print('❌ [AUTH_INTERCEPTOR] 处理401错误失败: $e');
      return false;
    }
  }

  /// 刷新Token（如果需要的话）
  Future<bool> _refreshTokenIfNeeded(AuthToken token) async {
    try {
      if (token.refreshToken.isEmpty) {
        print('⚠️ [AUTH_INTERCEPTOR] 刷新Token为空');
        return false;
      }
      
      final response = await _authRepository.refreshToken(token.refreshToken);
      
      if (response.isSuccess && response.data != null) {
        print('✅ [AUTH_INTERCEPTOR] Token刷新成功');
        return true;
      } else {
        print('❌ [AUTH_INTERCEPTOR] Token刷新失败: ${response.error}');
        return false;
      }
    } catch (e) {
      print('💥 [AUTH_INTERCEPTOR] Token刷新异常: $e');
      return false;
    }
  }

  /// 重试请求
  Future<Response> _retry(RequestOptions requestOptions) async {
    // 更新认证头
    await _addAuthHeader(requestOptions);
    
    // 创建新的Dio实例来避免拦截器循环
    final dio = Dio();
    
    // 复制原始请求的配置，但不包含拦截器
    dio.options = BaseOptions(
      baseUrl: requestOptions.baseUrl,
      connectTimeout: requestOptions.connectTimeout,
      receiveTimeout: requestOptions.receiveTimeout,
      headers: requestOptions.headers,
    );
    
    // 执行请求
    return await dio.request(
      requestOptions.path,
      data: requestOptions.data,
      queryParameters: requestOptions.queryParameters,
      options: Options(
        method: requestOptions.method,
        headers: requestOptions.headers,
        responseType: requestOptions.responseType,
        contentType: requestOptions.contentType,
        validateStatus: requestOptions.validateStatus,
        receiveDataWhenStatusError: requestOptions.receiveDataWhenStatusError,
        followRedirects: requestOptions.followRedirects,
        maxRedirects: requestOptions.maxRedirects,
        requestEncoder: requestOptions.requestEncoder,
        responseDecoder: requestOptions.responseDecoder,
      ),
    );
  }
}